import { TipsType } from "../../app_base/module/view/IView";
import { app } from "../../base";
import { View } from "../../app_cocos/View/View";
import { viewClass } from "../../app_cocos/View/CCPViewLoader";
import { viewAnalytics } from "../../app_base/module/view/ViewManager";

const { ccclass, property, menu } = cc._decorator;

@ccclass()
@menu("基础视图/TipsView")

export class TipsView extends View {
    @property({ type: [cc.Node], tooltip: "不同提示类型的节点, [0]常规提示，[1]警告提示，[2]错误提示" })
    private typNodes: cc.Node[] = [];

    @property(cc.Label)
    private tipsLabel: cc.Label = null;

    @property(cc.Vec2)
    private postion: cc.Vec2 = cc.v2(0, 100);

    @property({ type: cc.Float, tooltip: "显示停留时长" })
    private lengthOfStay: number = 1

    // @property({type:cc.Float, tooltip:"消失时长"})
    // private duration:number = 0.3;

    // @property({type:cc.Integer, tooltip:"消失位移距离(Y轴)"})
    // private distance:number = 80;

    public setData(contentStr: string, type: TipsType = TipsType.normal): void {
        this.tipsLabel.string = contentStr;
        for (let i = 0; i < this.typNodes.length; i++) {
            const element = this.typNodes[i];
            element.active = i == type;
            if (i == type) {
                app.timer.frameNext(this, () => {
                    let spriteFrame: cc.SpriteFrame = element.getComponent(cc.Sprite).spriteFrame;
                    element.width = Math.max(400, this.tipsLabel.node.width + spriteFrame.insetLeft + spriteFrame.insetRight);
                    this.tipsLabel.node.x = element.width > 400 ? -element.width / 2 + spriteFrame.insetLeft + this.tipsLabel.node.width / 2 : 0;
                });
            }
        }
    }

    public popup(): void {
        app.viewManager.scene().addToTopup(this);
        cc.tween(this.node).set({ x: this.postion.x, y: this.postion.y - 10, opacity: 0 })
            .to(0.1, { y: this.postion.y, opacity: 255 })
            .delay(this.lengthOfStay)
            .to(0.1, { /**y: this.distance, */opacity: 0 })
            .call(this.reset, this).start();
        app.viewManager.onViewEvent("open", this, this._onCreateNewTips);
    }

    private _onCreateNewTips(viewName: string): void {
        if ((viewName == "error" || viewName == "normal" || viewName == "warn") && !!this.node.parent) {
            this.node.y += this.node.height + 10;
        }
    }

    public reset(): void {
        app.viewManager.offViewEvent("open", this, this._onCreateNewTips);
        cc.Tween.stopAllByTarget(this.node);
        this.node.removeFromParent(false);
    }

}
